package scriptrunner.execution.cloud;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.jgroups.Address;

import communication.Communicator;
import communication.ParameterizedMessage;

import service.script.ScriptExecutionService;

public class CloudManager {
	
	private Communicator communicator;
	
	private static Map<String, CloudManager> managers = new HashMap<String, CloudManager>();
	
	private CloudManager(Communicator communicator) {
		this.communicator = communicator;
	}
	
	public static void createCloudManager(String cloudName, Communicator communicator) {
		CloudManager manager = new CloudManager(communicator);
		managers.put(cloudName, manager);
	}
	
	public static CloudManager getCloudManager(String cloudName) {
		return managers.get(cloudName);
	}
	
	public ParameterizedMessage sendMessageToRandomSlave(ParameterizedMessage msg) {
		return communicator.sendMessage(getRandomSlave(), msg);
	}
	
	public Address getRandomSlave() {
		List<Address> slaves = communicator.getSlavesByRole();
		int slaveCount = slaves.size();
		
		if (slaveCount == 0) {
			return null;
		}
		
		Random random = new Random();
		
		int randomSlaveIndex = random.nextInt(slaveCount);
		
		return slaves.get(randomSlaveIndex);
	}
	
	public Address getMaster() {
		return communicator.getMasterByRole();
	}
	
	public ParameterizedMessage sendMsg(Address address, ParameterizedMessage msg) {
		return communicator.sendMessage(address, msg);
	}
	
	public ParameterizedMessage sendMsgToMaster(ParameterizedMessage msg) {
		return communicator.sendMessage(getMaster(), msg);
	}


}
